package service

import (
	"net/http"

	"gitee.com/anxu/golang-web/src/config"
	"github.com/gorilla/sessions"
)

// Session session service
var Session *session

var store *sessions.FilesystemStore

const (
	defaultName = "session_id"
	defaultPath = ""
)

func init() {
	path := config.Config.Get("session.path", defaultPath).(string)
	key := config.Config.Get("security.key", EncryptKey).(string)
	store = sessions.NewFilesystemStore(path, []byte(key))

	name := config.Config.Get("session.name", defaultName).(string)
	Session = &session{sessionName: name}
}

type session struct {
	sessionName string
	session     *sessions.Session
	request     *http.Request
	response    http.ResponseWriter
}

// Start session start
func (s *session) Start(r *http.Request, w http.ResponseWriter) {
	s.session, _ = store.Get(r, s.sessionName)
	s.request = r
	s.response = w

	if s.session.IsNew {
		s.session.Save(r, w)
	}
	Logger.Info(s)
}

func (s *session) Get(key string) interface{} {
	if value, ok := s.session.Values[key]; ok {
		return value
	}
	return nil
}

func (s *session) Set(key string, value interface{}) {
	s.session.Values[key] = value
	defer s.session.Save(s.request, s.response)
}

func (s *session) Del(key string) {
	delete(s.session.Values, key)
	defer s.session.Save(s.request, s.response)
}
func (s *session) Destroy() {
	s.session.Values = nil
	defer s.session.Save(s.request, s.response)
}
